import React, { useState, useEffect } from "react";
import styles from "../css/Home.module.css";
import "../css/global.css";
import axios from "axios";
import { Swiper, Image } from "react-vant";
import { Loading } from "react-vant";
import { useNavigate, Link } from "react-router-dom";

export default function Home() {
  const navigate = useNavigate();
  const [data, setData] = useState(null);
  const [cartItems, setCartItems] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [indexRes, cartRes] = await Promise.all([
          axios.post("/mobile/index"),
          axios.post("/mobile/shopping", { id: "79" }),
        ]);
        setData(indexRes.data.data);
        setCartItems(cartRes.data.data || []); // 确保默认是数组
      } catch (err) {
        console.error("请求失败:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  // 移出购物车
  const handleRemoveFromCart = (productId, e) => {
    console.log(productId);
    console.log(cartItems);
    for (let i in cartItems) {
      if (cartItems[i].commodity_id == productId) {
        axios
          .post("mobile/shopping/del", {
            // 根据需求传递商品ID
            id: cartItems[i].id,
          })
          .then((response) => {
            console.log("商品已成功移出购物车", response.data);
            // 可根据实际返回的数据更新UI
          })
          .catch((error) => {
            console.error("接口请求失败", error);
          });
      }
    }
  };

  // 加入购物车
  const handleAddToCart = (product, e) => {
    axios
    .post("mobile/shopping/add", {
      // 根据需求传递商品ID
      commodity_id: product.id,
      user_id:JSON.parse(sessionStorage.getItem("user")).id,
      num:1
    })
    .then((response) => {
      console.log("商品已成功移出购物车", response.data);
      // 可根据实际返回的数据更新UI
    })
    .catch((error) => {
      console.error("接口请求失败", error);
    });
    e.stopPropagation(); // 阻止事件冒泡
    setCartItems([...cartItems, product]);
  };

  // 判断商品是否在购物车
  const isInCart = (productId) => {
    return cartItems.some(
      (item) => String(item.commodity_id) === String(productId)
    );
  };

  if (loading) {
    return (
      <Loading
        style={{
          display: "inline-flex",
          position: "fixed",
          left: "50%",
          top: "50%",
          transform: "translate(-50%, -50%)",
        }}
        size="24px"
        vertical
      >
        加载中...
      </Loading>
    );
  }
  console.log(data);
  console.log(cartItems);

  if (!data?.banner || !Array.isArray(data.banner)) {
    return <div>暂无轮播数据</div>;
  }

  return (
    <div className={styles.body}>
      <div className={styles.top_box}>
        {/* 顶部搜索框架 */}
        <div className={styles.search_box}>
          <img src={require("../img/search.png")} alt="" />
          <input type="text" placeholder="雅芝睡眠面膜" />
          <div className={styles.search_btn}>搜索</div>
        </div>
        {/* 轮播图 */}
        <div
          className={styles.demo_swiper}
          style={{
            padding: "0px",
            width: "95%",
            margin: "auto",
            marginTop: "10px",
          }}
        >
          <Swiper autoplay={3000} touchable={true} preventScroll={true}>
            {data.banner.map((item) => (
              <Swiper.Item
                touchable={true}
                preventScroll={true}
                key={item.id}
                style={{ height: 200 }}
              >
                {" "}
                {/* 使用唯一 id 作为 key */}
                <Image
                  touchable={true}
                  preventScroll={true}
                  loop={true}
                  src={"http://jingxun.kuxia.top/" + item.banner}
                  alt={item.title}
                />
              </Swiper.Item>
            ))}
          </Swiper>
        </div>
        {/* 菜单选项 */}
        <div className={styles.menu_box}>
          {console.log(data)}
          {data.classify.map((val) => {
            return (
              <div className={styles.menu_item} key={val.id}>
                <img
                  className={styles.menu_icon}
                  src={"http://jingxun.kuxia.top/" + val.icon}
                  alt=""
                />
                <p>{val.title}</p>
              </div>
            );
          })}
        </div>
      </div>
      {/* 热门榜单 */}
      <div className={styles.hot_box}>
        <div className={styles.hot_title}>
          <div className={styles.hot_title_left}>
            <img src={require("../img/fire.png")} alt="" />
            <p>热门榜单</p>
          </div>
          <div className={styles.hot_title_right}>
            更多
            <img src={require("../img/arrow-right-s-line.png")} alt="" />
          </div>
        </div>
        <div className={styles.hot_goods_box}>
          {data.hot.map((val) => {
            return (
              <div className={styles.hot_goods_item} key={val.id}>
                <img src={"http://jingxun.kuxia.top/" + val.image} alt="" />
                <p className={styles.hot_goods_name}>{val.title}</p>
                <p className={styles.hot_goods_price}>
                  <span className={styles.hot_goods_price_font}>￥</span>
                  {val.price}
                </p>
              </div>
            );
          })}
        </div>
      </div>

      {/* 选项 */}
      <div className={styles.option_box}>
        <p style={{ fontSize: "15px" }}>猜你喜欢</p>
        <p>美妆</p>
        <p>男装</p>
        <p>女装</p>
        <p>食品</p>
        <p>电器</p>
        <p>家电</p>
        <p>母婴</p>
        <p>百货</p>
      </div>

      {/* 商品瀑布流 - 关键修改部分 */}
      <div className={styles.commodity}>
        {data.commodity?.map((product) => (
          <div
            key={product.id}
            onClick={() => navigate(`/details/${product.id}`)}
            className={styles.waterfall_box}
          >
            <img
              src={`http://jingxun.kuxia.top/${product.image}`}
              alt={product.title}
            />
            <p className={styles.goods_name}>{product.title}</p>
            <div className={styles.commodity_price}>
              <p className={styles.commodity_price_font}>
                <span className={styles.hot_goods_price_font}>￥</span>
                {product.price}
              </p>
              {isInCart(product.id) ? (
                <img
                  src={require("../img/check-circle.png")}
                  onClick={(e) => handleRemoveFromCart(product.id, e)}
                  alt="已在购物车"
                  className={styles.cartButton}
                />
              ) : (
                <img
                  onClick={(e) => handleAddToCart(product, e)}
                  src={require("../img/accretion.png")}
                  alt="加入购物车"
                  className={styles.cartButton}
                />
              )}
            </div>
          </div>
        ))}
      </div>

      {/* 底部导航栏保持不变... */}
      <div className={styles.bottom_navigation}>
        <div className={styles.bottom_navigation_option}>
          <img
            className={styles.navigation_active}
            src={require("../img/home.png")}
            alt=""
          />
          <p className={styles.navigation_active}>首页</p>
        </div>
        <div className={styles.bottom_navigation_option}>
          <img src={require("../img/list_bulleted.png")} alt="" />
          <p>分类</p>
        </div>
        <div className={styles.bottom_navigation_option}>
          <Link to="/shopping">
            <img src={require("../img/shopping cart.png")} alt="" />
            <p>购物车</p>
          </Link>
        </div>
        <div className={styles.bottom_navigation_option}>
        <Link to="/Mine">
          <img src={require("../img/person.png")} alt="" />
          <p>我的</p>
          </Link>
        </div>
      </div>
    </div>
  );
}
